extends Node2D

var planets = []

var jam_step = 3 #seconds
var timer
var first_dispence_timer
var max_retries = 5

# Declare member variables here. Examples:
# var a = 2
# var b = "text"


# Called when the node enters the scene tree for the first time.
func _ready():
	randomize()
	timer = Timer.new()
	timer.wait_time = jam_step
	timer.connect("timeout",self,"on_time")
	timer.autostart = true
	first_dispence_timer = Timer.new()
	
	first_dispence_timer.wait_time = 0.5
	first_dispence_timer.one_shot = true
	first_dispence_timer.connect("timeout",self,"preliminary_dispence")
	first_dispence_timer.autostart = true

func preliminary_dispence():
	dispense_jams(1) # start with at least one jam for ppl not to wait

func on_mouse_activate():
	call_deferred("add_child",timer)
	call_deferred("add_child",first_dispence_timer)

func on_time():
	#print("tick")
	var intensity = 15
	var rand_iter = 100.0
	var rand_norm = 0
	for i in range(rand_iter):
		rand_norm += rand_range(-intensity,intensity)
	rand_norm /= rand_iter
	rand_norm = abs(rand_norm)
	#print(rand_norm)
	var jamnum = floor(rand_norm)
	dispense_jams(jamnum)

func dispense_jams(jamnum):
	for j in range(jamnum):
		for r in range(max_retries-1):
			var i = randi() % len(planets)
			if planets[i].jam == null:
				planets[i].add_random_jam()
				break
